<?php

/**
 * vehicle actions.
 *
 * @package    MVM Vehicle Showroom (r) showroom
 * @subpackage vehicle
 * @author     Bo Wang
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class vehicleActions extends sfActions {
  /**
   * Executes index action
   *
   * @param sfRequest $request A request object
   */
  public function executeIndex(sfWebRequest $request) {

    $this->vehicle = Doctrine::getTable('Vehicle')->
            find($request->getParameter('id'));
    $this->forward404Unless($this->vehicle);

    $enquiry = new Enquiry();
    $enquiry->setVehicleId($this->vehicle->getId());
    $this->form = new VehicleEnquiryForm($enquiry);

    if ($request->isMethod('post')) {
      $this->processForm($request, $this->form);
    }
    //301 redirect if slug is not the same
    $slug = preg_replace('/[^\d\w]+/', '_',strtolower($this->vehicle->getName()));

    if($request->getParameter('name')!=$slug){
      $this->redirect('vehicle/index?id='.$this->vehicle->getId().'&name='.$slug,301);
    }
    $this->getResponse()->setTitle($this->vehicle->getName().' @ '. sfConfig::get('app_company_name'));
  }

  public function executeEnquiryForm(sfWebRequest $request) {

    $this->vehicle = Doctrine::getTable('Vehicle')->
            find($request->getParameter('id'));
    $this->forward404Unless($this->vehicle);

    $enquiry = new Enquiry();
    $enquiry->setVehicleId($this->vehicle->getId());
    $this->form = new VehicleEnquiryForm($enquiry);

  }
  protected function processForm(sfWebRequest $request, sfForm $form) {

    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

    $resq = $request->getParameter($form->getName());
    if ($form->isValid()) {
      $enquiry = $form->save();

      $url = $request->getHost().$this->getController()->genUrl('@vehicle?id='.$enquiry->getVehicleId());
      $to = sfConfig::get('app_enquiry_email_account');
      $message = $this->getMailer()->composeAndSend(
              array($resq['email'] => $resq['name']),
              $to,
              'Vehicle Enquiry @ '.sfConfig::get('app_company_name').' '.date('d-m-Y'),
<<<EOF
Name: {$resq['name']}
Email: {$resq['email']}
Phone: {$resq['phone']}

Enquiry:
       {$resq['body']}

Vehicle Url: {$url}

EOF
      );
      $slug = preg_replace('/[^\d\w]+/', '_',strtolower($enquiry->getVehicle()->getName()));
      $this->getUser()->setFlash('notice', 'Your enquiry has been sent us!');
      $this->redirect('vehicle/index?id='.$enquiry->getVehicleId().'&name='.$slug);
    }
  }
}
